package com.recsmile.sgs.util;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtobufIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;

import java.io.Serializable;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by hanyuanliang on 16/8/23.
 */
public class SerializableUtil {
    private static ConcurrentHashMap<Class<?>, Schema> caches = new ConcurrentHashMap<Class<?>, Schema>();

    private static Objenesis objenesis = new ObjenesisStd(true);

    private SerializableUtil(){}

    private static <T> Schema<T> get(Class<T> cls){
        Schema<T> schema = caches.get(cls);
        if(schema == null){
            synchronized (SerializableUtil.class){
                if(schema == null){
                    schema = RuntimeSchema.getSchema(cls);
                    caches.put(cls,schema);
                }
            }
        }

        return schema;
    }

    public static <T> byte[] toByteArray(T t){
        LinkedBuffer linkedBuffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            return ProtobufIOUtil.toByteArray(t, (Schema<T>) get(t.getClass()), linkedBuffer);
        }catch (Exception e){
            e.printStackTrace();
            throw  new RuntimeException(e);
        }finally {
            linkedBuffer.clear();
        }
    }

    public static <T> T newInstance(byte[] array, Class<T> cls){
        T t= objenesis.newInstance(cls);
        ProtobufIOUtil.mergeFrom(array, t, (Schema<T>)get(t.getClass()));
        return t;

    }

    public static Objenesis getObjenesis() {
        return objenesis;
    }
}
